<?php

/*
 *
 */

class Model_Mediate_ReturnedMoneyPlan extends Model_BaseModel
{
    use Lib_BaseTraits;
    /**
     * 缓存前缀
     *
     * @var unknown
     */
    private static $tag = 'Model_Mediate_ReturnedMoneyPlan';
    /**
     * Undocumented variable.
     *
     * @var string
     */
    private $table = 'returned_money_plan';

    public function __construct()
    {
        // 选择连接的数据库
        parent::_init('mediation');
    }
    public function insert($savePlan,$savePlanDetail)
    {
        $this->dao->conn(false);
        $this->dao->noCache();
        $this->dao->beginTransaction();

        //添加计划
        $data = array();
        $sql = 'INSERT INTO `returned_money_plan`(';
        $sql .= '`' . implode('`,`', array_keys($savePlan)) . '`';
        $sql .= ')VALUES(:' . implode(',:', array_keys($savePlan)) . ')';
        foreach ($savePlan as $key => $value) {
            $data[':' . $key] = $value;
        }
        $plan_id = $this->dao->preparedSql($sql, $data)->lastInsertId();
        if (!$plan_id) {
            $this->dao->rollback();
            return false;
        }

        //计划详情
        $fields = array_keys($savePlanDetail[0]);
        array_push($fields,'planId');
        $sql = "INSERT INTO returned_money_plan_detail(";
        $sql .= '`' . implode('`,`', $fields) . '` )VALUES ';
        $str = '';
        $saveData = [];
        foreach ($savePlanDetail as $i => $val) {
            $val['planId'] = $plan_id;
            $str .= ',( ';
            $fieldstr = '';
            foreach (array_keys($val) as $field){
                $fieldstr .= ":{$field}{$i},";
                $saveData[":{$field}{$i}"] = $val[$field];
            }
            $str .=  trim($fieldstr, ',');
            $str .= ')';
        }

        $sql = $sql . trim($str, ',');
        $detail_res = $this->dao->preparedSql($sql, $saveData)->lastInsertId();
        if (!$detail_res) {
            $this->dao->rollback();
            return false;
        }
        $time = time();
        $sql = "UPDATE cases SET repayStatus='wait_repay',updateTime={$time} WHERE id = {$savePlan['caseId']}";
        $update_res = $this->dao->preparedSql($sql, [])->affectedCount();
        if (!$update_res) {
            $this->dao->rollback();
            return false;
        }
        $this->dao->commit();
        $this->dao->clearTag(self::$tag);
        $this->dao->clearTag('Model_Mediate_Case');
        return true;
    }
    public function updateTodayContactStutus(){
        $sql =  "UPDATE `returned_money_plan` SET todayContactStutus = 1 where todayContactStutus in (2,3)";
        return  $this->dao->conn(false)->noCache()->preparedSql($sql, [])->affectedCount();
    }
    public function cancelRepay($mediatorId,$caseId){
        $this->dao->conn(false);
        $this->dao->noCache();
        $this->dao->beginTransaction();
        $sql =  "UPDATE `returned_money_plan` SET status = 'cancel_repay' where caseId = {$caseId} and status <> 'finish_repay' and mediatorId <> {$mediatorId} ";
        $update_res = $this->dao->preparedSql($sql, [])->affectedCount();
        if (!$update_res) {
            $this->dao->rollback();
            return false;
        }
        $sql =  "UPDATE `returned_money_plan_detail` SET status = 'cancel_repay' where caseId = {$caseId} and  status = 'keep_plan' and mediatorId <> {$mediatorId} ";
        $update_res = $this->dao->preparedSql($sql, [])->affectedCount();
        if (!$update_res) {
            $this->dao->rollback();
            return false;
        }
        $this->dao->commit();
        $this->dao->clearTag(self::$tag);
        $this->dao->clearTag('Model_Mediate_ReturnedMoneyPlan');
        return true;
    }
    public function saveByIds($updateDta, $ids, $where = [],$pk)
    {
        $data = [];
        $sql = 'UPDATE `returned_money_plan` SET ';
        $sqlarr = array();
        foreach ($updateDta as $key => $value) {
            array_push($sqlarr, "`{$key}`=:$key");
            $data[":$key"] = $value;
        }
        $where_str = '';
        if (!empty($where)) {
            $where_str = 'AND '.implode(' AND ', $where);
        }
        $sql .= implode(',', $sqlarr);
        $sql .= " WHERE {$pk} in ({$ids}) {$where_str}";
        $res = $this->dao->conn(false)->noCache()->preparedSql($sql, $data)->affectedCount();
        $this->dao->clearTag(self::$tag);
        return $res;
    }
}
